package networking;

import java.io.*;
import java.net.Socket;

/**
 * function
 * Created by Administrator on 2017/1/4.
 */
public class SocketConnectionClientUtil {

    private String ipAddress;
    private Integer port;

    public SocketConnectionClientUtil(String ipAddress,Integer port){
        this.ipAddress = ipAddress;
        this.port = port;
    }

    public  void sendMessage(){

        try {
            //"192.168.0.7",8080
            Socket socket = new Socket(ipAddress,port);
            OutputStream output = socket.getOutputStream();
            //socket输出
            output.write("cao ni mabi!".getBytes());
            output.flush();
            output.close();

            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public  void receiveMessage(){
        byte[] bytes = new byte[1024*8];
        try {
            Socket socket = new Socket(ipAddress,port);
            InputStream in = socket.getInputStream();
            BufferedReader buf = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            //socket接收信息
            int msg = in.read();
            System.out.println("RECEIVE_MESSAGE:"+msg);

            String msgAddress =socket.getInetAddress().getHostAddress();
            String msgAddress1 =socket.getInetAddress().getHostName();
            System.out.println("RECEIVE_MESSAGE:"+msgAddress+"*********"+msgAddress1);

            while(buf.readLine()!=null){
                System.out.println("OUTPUT_MESSAGE:"+buf.readLine());
            }

            in.close();
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
